package pear.hostingClasses;

import pear.other.HostingInterface;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import pear.gui.table.FilePart;
import pear.other.Helper;

/**
 *
 * @author Dingo
 */
public class PCTRHosting extends Hosting implements HostingInterface {

    public PCTRHosting() {
        ID = 1335897457160L;
        NAME = "PCTR";
        DESCRIPTON = "Raczej nie polecany na duży upload";
        MAXSIZE = 10;
    }
    
    @Override
    public String sendFile(FilePart filePart, File file) throws MalformedURLException, IOException {
        double len = file.length();//tu są Bajty
        double size = len / 1024;//tu są kB!
        filePart.setSize(size); //rozmiar w kB
        filePart.setReminingSize(size);//pozostały rozmiar do wysłania w kB
        filePart.setProgress(0);

        /*
         * Proces wsyłania
         */
        int bufferSize = 102400;
        String boundary = Long.toHexString(System.currentTimeMillis());

        HttpURLConnection connection = (HttpURLConnection) new URL("http://pctr.pl/").openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setChunkedStreamingMode(bufferSize);
        PrintWriter writer = null;
        String charset = "UTF-8";
        String CRLF = "\r\n";
        try {
            OutputStream output = connection.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

            // Send normal param.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"MAX_FILE_SIZE\"").append(CRLF);
            writer.append(CRLF);
            writer.append("16777216").append(CRLF).flush();

            // Send binary file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + "test2.png" + "\"").append(CRLF);
            writer.append("Content-Type: image/png").append(CRLF);
            writer.append(CRLF).flush();
            InputStream input = null;

            Long startTime = System.currentTimeMillis();
            Long deltaTime;

            try {
                input = new FileInputStream(file);
                byte[] buffer = new byte[bufferSize];//tu jest 100kB
                for (int length = 0, i = 0; (length = input.read(buffer)) > 0; i++) {
                    filePart.setReminingSize(size);
                    filePart.setProgress((int) ((filePart.getSize() - size) / filePart.getSize() * 100));
                    System.out.println("Pozostało: " + size);
                    System.out.println("Process: " + filePart.getProgress());


                    output.write(buffer, 0, length);
                    size -= 100;

                    if (i % 10 == 9) {
                        //100*10kB * 1s / np. 0.29ms
                        deltaTime = System.currentTimeMillis() - startTime;
                        double kBps = 1000 / (double) (deltaTime) * 1000;
                        if (deltaTime != 0) {
                            System.out.println("Prędkość: " + kBps + " kBps");
                        } else {
                            System.out.println("Prędkość: 0 kBps ;p");
                        }
                        startTime = System.currentTimeMillis();
                    }
                }
                output.flush();
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException logOrIgnore) {
                    }
                }
            }
            writer.append(CRLF).flush();

            //dodaj zwykle
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"send\"").append(CRLF);
            writer.append(CRLF);
            writer.append("Wrzuć plik").append(CRLF).flush();

            //koniec
            writer.append("--" + boundary + "--").append(CRLF);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        
        /*
         * Pobierz odpowiedź i ją zwróć
         */
        InputStream is = connection.getInputStream();
        filePart.setProgress(100);
        return Helper.inputStreamToString(is);
    }

    @Override
    public String getUploadLink(String pageString) {
        Pattern p = Pattern.compile("codedirect\" value=\"([^\"].)+");
        Matcher m = p.matcher(pageString);
        m.find(); //znajdz wystąpienie
        String tmp = m.group(); //wpisz stringa od m.start do m.end
        return tmp.split("\"")[2]; //wyslij 3 wystapienie po "
    }

    @Override
    public String getDownloadLink(String uploadLink) {
        return uploadLink;
    }

    @Override
    public String toString() {
        return NAME;
    }
    
}
